clc; close all; clear;
addpath('../02_Functions');

%------------------------------------------------------------------------%
% This file creates figure 1 in the paper 
%------------------------------------------------------------------------%

% load e-mini contracts
data = load('../01_Data/es_trades_5minute_EST.mat');

No_trades                                                               = data.trades_per_min_mat;
No_contracts                                                            = data.trade_quantity_per_min_mat;
Signed_volume                                                           = data.signed_vol_per_min_mat;

% choose sample period ---------------------------------------------------------------------------------- %


start_date      = datenum(1998,1,5);
finish_date     = datenum(2021,1,5);

beg             = find(data.caldt_daily==start_date);
fin             = find(data.caldt_daily==finish_date);

caldt           = data.caldt_daily(beg:fin);
No_trades       = No_trades(beg:fin,:); 
Volume          = No_contracts(beg:fin,:); 

fprintf(1,'********************************\n')
fprintf(1,'Sample: Emini          \n')
fprintf('begin %12s  \n',datestr(caldt(1)))
fprintf('finish %12s  \n',datestr(caldt(end)))
fprintf(1,'********************************\n')

%------------------------------------------------------------------------%

ADIndex           = 1 : 288;              % 18:10 - 18:00
ONIndex           = 1 : 186;              % 18:10 - 9:30
IDIndex           = 187 : 267;            % 9:30 - 16:15

% ON ID VOLUME TIME SERIES 
Volume_ON         = sum(Volume(:,ONIndex),2);  
Volume_ID         = sum(Volume(:,IDIndex),2);  

caldt             = datetime(caldt,'ConvertFrom','datenum');
TT                = timetable(caldt,Volume_ON,Volume_ID,'VariableNames',{'volumeON','volumeID'});
TT                = retime(TT,'monthly','mean');
TT.caldt          = dateshift(TT.caldt,'end','month');
Volume_ON_monthly = TT.volumeON;
Volume_ID_monthly = TT.volumeID;
caldt_monthly     = TT.caldt;
caldt_monthly     = datenum(caldt_monthly);

%------------------------------------------------------------------------%

% load the big SP contract
[data , text]   = xlsread('../01_data/EOD_Elektron.xlsx','SP');

caldt_temp      = x2mdate(data(:,1));
RIC_temp        = text(2:end,2);
price_temp      = data(:,4);
volume_temp     = data(:,5);

indx            = find(strcmp(RIC_temp,'SPc1'));
caldt_SPc1      = caldt_temp(indx,1);
price_SPc1      = price_temp(indx,1);
volume_SPc1     = volume_temp(indx,1);

indx            = find(strcmp(RIC_temp,'SPc2'));
caldt_SPc2      = caldt_temp(indx,1);
price_SPc2      = price_temp(indx,1);
volume_SPc2     = volume_temp(indx,1);

% ----------- DATE VECTOR

caldt_elektron  = [];
counter         = 1;

for t = year(caldt_SPc1(1)) : 1 : year(caldt_SPc1(end))
    for m = 1 : 12
        caldt_elektron(counter,1) = datenum(t,m,28);
        counter = counter + 1;
    end    
end

% ------------ BUILD MONTHLY SERIES
caldt_elektron = caldt_elektron(1:end-6);

for t = 1 : length(caldt_elektron)
    indx1 = find(year(caldt_SPc1) == year(caldt_elektron(t)) & month(caldt_SPc1) == month(caldt_elektron(t)));
    indx2 = find(year(caldt_SPc2) == year(caldt_elektron(t)) & month(caldt_SPc2) == month(caldt_elektron(t)));
    volume_SP(t,1) = [nansum(volume_SPc1(indx1)) + nansum(volume_SPc2(indx2))]/22*5;
end

%------------------------------------------------------------------------%

time_span = 1982 : 2 : 2022;
x_ticks = datenum(time_span, 1, ones(1, length(time_span)));
x_labels = num2str(time_span');

FS = 18;

figure;
plot(caldt_elektron , volume_SP,'Linestyle','-','Linewidth',3);
hold on
plot(caldt_monthly , Volume_ID_monthly,'Linestyle','-','Linewidth',3,'Color',rgb('green'));
hold on
plot(caldt_monthly , Volume_ON_monthly,'Linestyle','-','Linewidth',3,'Color',rgb('red'));
hold on
legend('5 x SP (ID + ON)','ES ID','ES ON','Location','NorthWest')
xlabel('Year' )
ylabel('Daily Volume Traded (No. of Contracts)' )
set(gca,'XTick' , x_ticks)
xticklabels(x_labels)
xtickangle(90)
xlim([min(caldt_elektron)-252 max(caldt_elektron)+252])

% finally compute yearly break down. 
years = unique(year(caldt_monthly));
percent_split = [];
for t = 1 : length(years)
    indx = find(year(caldt_monthly) == years(t));
    percent_split(t,1) = sum(Volume_ON_monthly(indx))/sum([Volume_ON_monthly(indx)+Volume_ID_monthly(indx)]);
end

x_ticks = years;
years_string = num2str(years);

years_string = years_string(:,end-1:end);

figure;
p1= bar(years,100*percent_split);
set(p1(1),'FaceColor','red');
set(p1(1),'BarWidth',1.0);
xlabel('Year' )
ylabel('Percentage of E-mini trade in the ON session' )
hold on
set(gca,'XTick',x_ticks,'XTickLabel',years_string);
xlim([years(1)-1,years(end)+1])

